package dao;

import entity.Fruit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FruitDao extends BaseDao {
    Connection conn =null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    public List<Fruit>list(){
        List<Fruit>list = new ArrayList<Fruit>();
        try {
            conn = super.getConnection();
            String sql = "SELECT*FROM fruit";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                Fruit f = new Fruit();
                f.setFruitId(rs.getInt("fruitId"));
                f.setType(rs.getString("type"));
                f.setBreed(rs.getString("breed"));
                f.setArea(rs.getString("area"));
                f.setBrief(rs.getString("brief"));
                f.setWeight(rs.getInt("weight"));
                f.setPrice(rs.getString("price"));
                list.add(f);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll(conn,pstmt,rs);
        }
        return list;
    }

    public Fruit fruitId(String fruitId){
        Fruit f = new Fruit();
        try {
            conn = super.getConnection();
            String sql = "SELECT*FROM fruit WHERE fruitId=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, Integer.parseInt(fruitId));
            rs=pstmt.executeQuery();
            if (rs.next()){
                f.setFruitId(rs.getInt("fruitId"));
                f.setType(rs.getString("type"));
                f.setBreed(rs.getString("breed"));
                f.setArea(rs.getString("area"));
                f.setBrief(rs.getString("brief"));
                f.setWeight(rs.getInt("weight"));
                f.setPrice(rs.getString("price"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll(conn,pstmt,rs);
        }
        return f;
    }

    public int delete(int fruitId){
        int result = 0;
        try {
            conn=super.getConnection();
            String sql = "DELETE FROM fruit WHERE fruitId = ?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,fruitId);
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll(conn,pstmt,null);
        }
        return result;
    }
}
